﻿namespace m3u2txt
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.IO;
    using System.Text.RegularExpressions;

    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("使用方法: m3u2txt <inputFilePath> <outputFilePath>");
                return;
            }

            string inputFile = args[0];  // 输入文件路径
            string outputFile = args[1]; // 输出文件路径

            if (!File.Exists(inputFile))
            {
                Console.WriteLine($"输入文件不存在: {inputFile}");
                return;
            }

            Dictionary<string, List<string>> txtDic = new Dictionary<string, List<string>>();

            try
            {
                using (StreamReader reader = new StreamReader(inputFile))
                //using (StreamWriter writer = new StreamWriter(outputFile))
                {
                    string currentCategory = "";
                    string line;

                    while ((line = reader.ReadLine()) != null)
                    {
                        line = line.Trim();

                        // 跳过非有效内容的行
                        if (string.IsNullOrEmpty(line) || line.StartsWith("#EXTM3U"))
                            continue;

                        if (line.StartsWith("#EXTINF"))
                        {
                            // 提取频道名称和分组信息
                            string channelName = ExtractAttribute(line, "tvg-name");
                            string groupTitle = ExtractAttribute(line, "group-title");

                            // 读取下一行作为 URL
                            string url = reader.ReadLine()?.Trim();

                            if (string.IsNullOrEmpty(groupTitle))
                            {
                                groupTitle = "默认";
                            }

                            if (!txtDic.ContainsKey(groupTitle))
                            {
                                txtDic.Add(groupTitle, new List<string>());
                            }

                            if (!string.IsNullOrEmpty(channelName) && !string.IsNullOrEmpty(url))
                            {
                                txtDic[groupTitle].Add($"{channelName},{url}");
                            }

                            //// 如果分组信息变更，则写入新分组标记
                            //if (!string.IsNullOrEmpty(groupTitle) && groupTitle != currentCategory)
                            //{
                            //    currentCategory = groupTitle;
                            //    writer.WriteLine($"{currentCategory},#genre#");
                            //}

                            //// 读取下一行作为 URL
                            //string url = reader.ReadLine()?.Trim();
                            //if (!string.IsNullOrEmpty(channelName) && !string.IsNullOrEmpty(url))
                            //{
                            //    writer.WriteLine($"{channelName},{url}");
                            //}
                        }
                    }
                }

                using (StreamWriter writer = new StreamWriter(outputFile))
                {
                    foreach (var it in txtDic)
                    {
                        var groupName = it.Key;
                        writer.WriteLine(string.Empty);
                        writer.WriteLine($"{groupName},#genre#");

                        foreach (var tt in it.Value)
                        {
                            writer.WriteLine(tt);
                        }
                    }
                }

                Console.WriteLine($"转换完成，结果已保存到 {outputFile}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 从 EXTINF 行中提取指定属性的值
        /// </summary>
        /// <param name="line">EXTINF 行</param>
        /// <param name="attributeName">属性名称</param>
        /// <returns>属性值</returns>
        static string ExtractAttribute(string line, string attributeName)
        {
            var match = Regex.Match(line, $@"{attributeName}=""(.*?)""");
            return match.Success ? match.Groups[1].Value : "";
        }
    }

}
